package com.yiwei.zhh.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.library.SuperButton;
import com.yiwei.zhh.R;
import com.yiwei.zhh.api.Api;
import com.yiwei.zhh.api.bean.PayInfoBean;
import com.yiwei.zhh.api.bean.ServiceDaikouBean;
import com.yiwei.zhh.api.bean.ServiceFeeTongGuan;
import com.yiwei.zhh.constant.Const;
import com.yiwei.zhh.model.PayInfoModel;
import com.yiwei.zhh.util.Network;
import com.yiwei.zhh.util.RxLifeUtil;
import com.yiwei.zhh.util.ToastUtil;
import com.yiwei.zhh.util.Util;
import com.yiwei.zhh.view.BankSelectDialog;
import com.yiwei.zhh.view.V19FrameLayout;

import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.beecloud.BCPay;
import cn.beecloud.BeeCloud;
import cn.beecloud.async.BCCallback;
import cn.beecloud.async.BCResult;
import cn.beecloud.entity.BCPayResult;

/**
 * Created by Administrator on 2018/6/10.
 */

public class ServiceFeePayActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_money)
    TextView txtMoney;
    @BindView(R.id.cb_one)
    ImageView cbOne;
    @BindView(R.id.cb_two)
    ImageView cbTwo;
    @BindView(R.id.layout_bank_pay)
    LinearLayout layoutBankPay;
    @BindView(R.id.txt_bank)
    TextView txtBank;
    @BindView(R.id.layout_bank_select)
    LinearLayout layoutBankSelect;
    @BindView(R.id.txt_tips)
    TextView txtTips;
    @BindView(R.id.btn_pay)
    SuperButton btnPay;
    @BindView(R.id.txt_time)
    TextView txtTime;
    @BindView(R.id.layout_alipay_pay)
    LinearLayout layoutAlipayPay;
    private Unbinder unbinder;
    private ProgressDialog progressDialog;
    private PayHandler mHandler;
    private String toastMsg;

    private BankSelectDialog bankSelectDialog;
    private static final String WX_APP = "WX_APP";
    private static final String ALI_APP = "ALI_APP";
    private static final String ACCOUNT = "BAG";
    private String selectWays = ALI_APP;
    private String pay_way;
    private String deal_id;
    private PayInfoModel.DataBean pay_info_data;
    private Handler handler = new Handler();
    private long leftTime;
    private String bankcard;
    private String bankcard_id;
    private String pay_no;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_fee_pay);
        initBar();
        unbinder = ButterKnife.bind(this);
        init();
    }


    Runnable update_thread = new Runnable() {
        @Override
        public void run() {
            leftTime--;
            if (leftTime > 0) {
                //倒计时效果展示
                String formatLongToTimeStr = Util.formatLongToTimeStr(leftTime);
                txtTime.setText(formatLongToTimeStr);
                //每一秒执行一次
                handler.postDelayed(this, 1000);
            } else {//倒计时结束
                //处理业务流程

                //发送消息，结束倒计时
                Message message = new Message();
                message.what = 1;
                handlerStop.sendMessage(message);
            }
        }
    };
    final Handler handlerStop = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    leftTime = 0;
                    handler.removeCallbacks(update_thread);
                    break;
            }
            super.handleMessage(msg);
        }

    };


    private void init() {
        txtTitle.setText("服务付费支付");
        initPay();
        mHandler = new PayHandler(this);

        bankSelectDialog = new BankSelectDialog(this);
        bankSelectDialog.setIsServiceFee(true);
        bankSelectDialog.setOnSelect(new BankSelectDialog.OnSureListener() {
            @Override
            public void onSure(String id, String bankcard) {
                bankcard_id = id;
                txtBank.setText(bankcard.substring(0, 3) + "****" + bankcard.substring(bankcard.length() - 4, bankcard.length()));

            }
        });

        deal_id = getIntent().getStringExtra("deal_id");
        getPayInfo(deal_id);
    }

    //1、获取beecloud支付信息（支付服务费信息）
    public void getPayInfo(String deal_id) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        PayInfoBean bean = new PayInfoBean();
        bean.deal_id = deal_id;
        Api.api_service.getPayInfo(bean).compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.getStatus() == 1) {
                        setData(result.data);
                    } else if (result.getStatus() == 2) {
                        txtTitle.setText("划扣中");
                        btnPay.setText("划扣中");
                        layoutBankPay.setEnabled(false);
                        layoutAlipayPay.setEnabled(false);
                        layoutBankSelect.setEnabled(false);
                        btnPay.setShapeSolidColor(0xffE4E4EE).setUseShape();
                        btnPay.setEnabled(false);

                        txtMoney.setText(result.data.money);
                        leftTime = Long.valueOf(result.data.order_validate) - new Date().getTime() / 1000;
                        handler.postDelayed(update_thread, 1000);

                        if (result.data.userbank != null) {
                            if (!TextUtils.isEmpty(result.data.userbank.bankcard_no)) {
                                bankcard = result.data.userbank.bankcard_no;
                                bankcard_id = result.data.userbank.bankcard_id;
                                txtBank.setText(bankcard);
                            }

                        }
                    } else {
                        ToastUtil.makeText(this, result.getMsg());
                    }
                });
    }

    //2 获取服务费划扣
    public void getServiceDaikou(String deal_id) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        ServiceFeeTongGuan bean = new ServiceFeeTongGuan();
        bean.pay_no = pay_no;
        bean.deal_id = deal_id;
        bean.bankcard_id = bankcard_id;
        Api.api_service.getServiceFeeTongGuan(bean).compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.getStatus() == 1) {
                        ToastUtil.makeText(this, result.data);
                        finish();
                    } else if (result.getStatus() == 2) {
                        txtTitle.setText("划扣中");
                        btnPay.setText("划扣中");
                        btnPay.setShapeSolidColor(0xffE4E4EE).setUseShape();
                        btnPay.setEnabled(false);
                        layoutBankPay.setEnabled(false);
                        layoutAlipayPay.setEnabled(false);
                        layoutBankSelect.setEnabled(false);
                    } else {
                        ToastUtil.makeText(this, result.getMsg());
                    }

                });
    }

    private void setData(PayInfoModel.DataBean data) {


        txtMoney.setText(data.money);
        pay_info_data = data;

        leftTime = Long.valueOf(data.order_validate) - new Date().getTime() / 1000;

        handler.postDelayed(update_thread, 1000);
        pay_no = data.pay_no;

        if (data.userbank != null) {
            if (!TextUtils.isEmpty(data.userbank.bankcard_no)) {
                bankcard = data.userbank.bankcard_no;
                bankcard_id = data.userbank.bankcard_id;
                txtBank.setText(bankcard);
            }

        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        leftTime = 0;
        handler.removeCallbacks(update_thread);

        BCPay.detachWechat();
        bcCallback = null;
        mHandler = null;
        //清理当前的activity引用
        BCPay.clear();
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        unbinder.unbind();
        unbinder = null;
    }


    private void initPay() {

        BeeCloud.setSandbox(false);
        //     正式网Appid和secret
        BeeCloud.setAppIdAndSecret(Const.BeeCloud.APP_ID,
                Const.BeeCloud.APP_Secret);
//        }


        // 如果用到微信支付，在用到微信支付的Activity的onCreate函数里调用以下函数.
        // 第二个参数需要换成你自己的微信AppID.
//        wx8f9ffda903463ae8
        String initInfo = BCPay.initWechatPay(this, Const.BeeCloud.WECHAT_ID);
        if (initInfo != null) {
            Toast.makeText(this, "微信初始化失败：" + initInfo, Toast.LENGTH_LONG).show();
        }
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("处理中，请稍候...");
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
    }


    private void goToPay(String title, double money, String bill_no) {
//        Map<String, String> mapOptional = new Gson().fromJson(PayOrderitem.optional, new TypeToken<HashMap<String, String>>() {
//        }.getType());
        Map<String, String> mapOptional = new HashMap<>();
        mapOptional.put("app", Const.getPayOptional());
//        Map<String, String> mapOptional = new HashMap<>();
//        mapOptional.put("disable_pay_channels", "credit_group");
        if (selectWays.equals(ALI_APP)) {
//                    支付宝
            progressDialog.show();
            BCPay.getInstance(this).reqAliPaymentAsync(
                    title,
                    (int) (money * 100),
                    bill_no,
                    mapOptional,
                    bcCallback);
        } else if (selectWays.equals(WX_APP)) {
//                    微信
            progressDialog.show();
            //对于微信支付, 手机内存太小会有OutOfResourcesException造成的卡顿, 以致无法完成支付
            //这个是微信自身存在的问题
//            Log.i("dasdasddas", BCPay.isWXAppInstalledAndSupported() + "aa" + BCPay.isWXPaySupported());
            if (BCPay.isWXAppInstalledAndSupported() &&
                    BCPay.isWXPaySupported()) {
                BCPay.getInstance(this).reqWXPaymentAsync(
                        title,               //订单标题
                        (int) (money * 100),  //金额
                        bill_no,  //订单流水号
                        mapOptional,            //扩展参数(可以null)
                        bcCallback);            //支付完成后回调入口

            } else {
                ToastUtil.makeText(this,
                        "您尚未安装微信或者安装的微信版本不支持").show();
                progressDialog.dismiss();
            }
        }
    }

    @OnClick({R.id.layout_alipay_pay, R.id.layout_bank_pay, R.id.layout_bank_select, R.id.btn_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_alipay_pay:
                cbOne.setImageResource(R.mipmap.img_pay_check);
                cbTwo.setImageResource(R.mipmap.img_pay_uncheck);
                pay_way = "0";
                break;
            case R.id.layout_bank_pay:
                cbOne.setImageResource(R.mipmap.img_pay_uncheck);
                cbTwo.setImageResource(R.mipmap.img_pay_check);
                pay_way = "1";
                break;
            case R.id.layout_bank_select:
                bankSelectDialog.show();
                break;
            case R.id.btn_pay:
                if (leftTime <= 0) {
                    ToastUtil.makeText(this, "订单已过期");
                    return;
                }
                if (TextUtils.isEmpty(pay_way)) {
                    ToastUtil.makeText(this, "支付方式不能为空");
                    return;
                }
                if (TextUtils.isEmpty(bankcard)) {
                    ToastUtil.makeText(this, "银行卡不能为空");
                    return;
                }
                if (pay_way.equals("0")) {
                    goToPay(pay_info_data.name, Double.valueOf(pay_info_data.money), pay_info_data.pay_no);
                } else {
                    getServiceDaikou(deal_id);
                }
                break;
        }
    }

    @OnClick(R.id.btn_back)
    public void onViewClicked() {
        finish();
    }


    private static class PayHandler extends Handler {
        WeakReference<ServiceFeePayActivity> mActivityReference;

        PayHandler(ServiceFeePayActivity activity) {
            mActivityReference = new WeakReference<ServiceFeePayActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final ServiceFeePayActivity activity = mActivityReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        //如果用户手机没有安装银联支付控件,则会提示用户安装
                        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                        builder.setTitle("提示");
                        builder.setMessage("完成支付需要安装或者升级银联支付控件，是否安装？");

                        builder.setNegativeButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
//                                        UPPayAssistEx.installUPPayPlugin(activity);
                                        dialog.dismiss();
                                    }
                                });

                        builder.setPositiveButton("取消",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                        builder.create().show();
                        break;
                    case 2:
                        Toast.makeText(activity, activity.toastMsg, Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }
    }


    //支付结果返回入口
    private BCCallback bcCallback = new BCCallback() {
        @Override
        public void done(final BCResult bcResult) {
            final BCPayResult bcPayResult = (BCPayResult) bcResult;
            //此处关闭loading界面
            progressDialog.dismiss();

            //根据你自己的需求处理支付结果
            String result = bcPayResult.getResult();
            /*
              注意！
              所有支付渠道建议以服务端的状态金额为准，此处返回的RESULT_SUCCESS仅仅代表手机端支付成功
            */
            Message msg = mHandler.obtainMessage();
            //单纯的显示支付结果
            msg.what = 2;
            if (result.equals(BCPayResult.RESULT_SUCCESS)) {
                toastMsg = "用户支付成功";
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        getReportResult(money, "1", notice_sn);
//                        Util.startActivity(OilcardOrderPayMoneyActivity.this, MyOrderActivity.class);
                        finish();
                    }
                });
            } else if (result.equals(BCPayResult.RESULT_CANCEL))
                toastMsg = "用户取消支付";
            else if (result.equals(BCPayResult.RESULT_FAIL)) {
                toastMsg = "支付失败, 原因: " + bcPayResult.getErrCode() +
                        " # " + bcPayResult.getErrMsg() +
                        " # " + bcPayResult.getDetailInfo();

                /**
                 * 你发布的项目中不应该出现如下错误，此处由于支付宝政策原因，
                 * 不再提供支付宝支付的测试功能，所以给出提示说明
                 */
                if (bcPayResult.getErrMsg().equals("PAY_FACTOR_NOT_SET") &&
                        bcPayResult.getDetailInfo().startsWith("支付宝参数")) {
                    toastMsg = "支付失败：由于支付宝政策原因，故不再提供支付宝支付的测试功能，给您带来的不便，敬请谅解";
                }

                /**
                 * 以下是正常流程，请按需处理失败信息
                 */

                if (bcPayResult.getErrMsg().equals(BCPayResult.FAIL_PLUGIN_NOT_INSTALLED)) {
                    //银联需要重新安装控件
                    msg.what = 1;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        getReportResult(money, "2", notice_sn);
                    }
                });

            } else if (result.equals(BCPayResult.RESULT_UNKNOWN)) {
                //可能出现在支付宝8000返回状态
                toastMsg = "订单状态未知";
            } else {
                toastMsg = "invalid return";
            }

            mHandler.sendMessage(msg);
        }
    };
}
